package com.eqdd.yiqidian.ui;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.eqdd.nextinputs.Scheme;
import com.eqdd.nextinputs.StaticScheme;
import com.eqdd.yiqidian.MineAuActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.AreaBean;
import com.eqdd.yiqidian.bean.BaseBean;
import com.eqdd.yiqidian.bean.EditBean;
import com.eqdd.yiqidian.bean.IDCardBean;
import com.eqdd.yiqidian.bean.User;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonCallBack;
import com.eqdd.yiqidian.ui.base.BaseMultiEditActivity;
import com.eqdd.yiqidian.ui.select.SelectTimeWithLunarActivity;
import com.eqdd.yiqidian.utils.EncryptUtil;
import com.eqdd.yiqidian.utils.FileUtil;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.GsonUtils;
import com.eqdd.yiqidian.utils.MultiChooseUtil;
import com.eqdd.yiqidian.utils.PhotoHttpUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;

import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;


import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.ISelectAble;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MineAuActivity extends BaseMultiEditActivity {

    private String[] titles = new String[]{
            "证件上传",
            "身份证正面照",
            "身份证反面照",
            "本人手持身份证照",
            "籍贯（必选）",
            "户口性质（必选）",
            "生日祝福日期（必选）",
            "邮箱（必选）",
            "真实姓名",
            "身份证号",
            "性别",
            "出生日期",
            "民族",
            "户籍"
    };
    private String[] titleTexts = new String[]{
            "证件上传",
            "身份证正面照",
            "身份证反面照",
            "本人手持身份证照",
            "籍贯（必选）",
            "户口性质（必选）",
            "生日祝福日期（必选）",
            "邮箱（必选）",
            "真实姓名",
            "身份证号",
            "性别",
            "出生日期",
            "民族",
            "户籍"
    };
    private String[] hintTexts = new String[]{
            "未选择",
            "未选择",
            "未选择",
            "未选择",
            "请选择",
            "请选择",
            "请选择",
            "请输入",
            "从身份证信息读取",
            "从身份证信息读取",
            "从身份证信息读取",
            "从身份证信息读取",
            "从身份证信息读取",
            "从身份证信息读取"
    };
    private String[] tipTexts = new String[]{
            "身份证正面",
            "身份证反面",
            "手持身份证",
            "个人正面照",
            "请输入姓名",
            "请输入姓名",
            "请输入姓名",
            null,
            null,
            "请输入身份证号",
            null,
            "请输入邮箱",
            "请输入手机号",
            "生日"
    };
    private int[] types = new int[]{
            4, 4, 4, 4, 4, 1, 4, 0, 4, 4, 4, 4, 4, 4
    };
    private int[] decoders = new int[]{7};
    String imagePathIDCardFront;
    String imagePathIDCardBehand;
    String imagePathIDCardWith;
    String imagePathZhengjianzhao;
    private MineAuActivityCustom dataBinding;
    private boolean isIDCardGet = false;
    private String msg;
    private List<AreaBean> areaBean;
    private BottomDialog areaDialog;
    private List<LocalMedia> localList = new ArrayList<>();
    private int choosed;
    private List<LocalMedia> selectList;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_mine_au);
        initTopTitleBar(View.VISIBLE, "个人认证");
        initTopRightText("提交", (v) -> {
            String sex = ((TextView) quickAdapter.getViewByPosition(10, R.id.tv_vertical_content)).getText().toString().trim();
            if (checkInfo()) {
                int age = getAge();
                System.out.println(1 + imagePathZhengjianzhao);
                System.out.println(2 + imagePathIDCardFront);
                System.out.println(3 + imagePathIDCardBehand);
                System.out.println(4 + imagePathIDCardWith);
                OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.USER_AUTHEN)
                        .params("userGuid", user.getGuid())
                        .params("name", ((TextView) quickAdapter.getViewByPosition(8, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("idnum", ((TextView) quickAdapter.getViewByPosition(9, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("sex", "男".equals(sex.trim()) ? "0" : "1")
                        .params("ptel", user.getUname())
                        .params("nation", ((TextView) quickAdapter.getViewByPosition(12, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("date", ((TextView) quickAdapter.getViewByPosition(11, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("pnative", ((TextView) quickAdapter.getViewByPosition(4, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("mail", ((TextView) quickAdapter.getViewByPosition(7, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("rdate", ((TextView) quickAdapter.getViewByPosition(6, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("age", age + "")
                        .params("user", user.getUname())
                        .params("housetype", ((TextView) quickAdapter.getViewByPosition(5, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("houseadress", ((TextView) quickAdapter.getViewByPosition(13, R.id.tv_vertical_content)).getText().toString().trim())
                        .params("iphoto", new File(imagePathZhengjianzhao))
                        .params("idumfrontphoto", new File(imagePathIDCardFront))
                        .params("idumbackphoto", new File(imagePathIDCardBehand))
                        .params("withidumphoto", new File(imagePathIDCardWith))
                        .execute(new DialogCallBack<HttpResult>(MineAuActivity.this) {
                            @Override
                            public void onSuccess(Response<HttpResult> response) {
                                HttpResult baseBean = response.body();
                                ToastUtil.showShort(baseBean.getMsg());
                                if (baseBean.getStatus() == 200) {
                                    Schedulers.io().createWorker().schedule(() -> {
                                        FileUtil.cleanCacheImage();
                                        clearData();
                                    });
                                    HashMap<String, String> map = new HashMap<>();
                                    map.put("u1", user.getUname());
                                    map.put("u2", EncryptUtil.sha1(SPUtil.getParam(Config.PASS, "") + "EQD"));
                                    OkGo.<HttpResult<User>>post(HttpConfig.BASE_URL + HttpConfig.LOGIN)
                                            .params(map)
                                            .execute(new JsonCallBack<HttpResult<User>>() {
                                                @Override
                                                public void onSuccess(Response<HttpResult<User>> response) {
                                                    HttpResult<User> httpResult = response.body();
                                                    ToastUtil.showShort(httpResult.getMsg());
                                                    if (httpResult.getStatus() == 200) {
                                                        GreenDaoUtil.insert(httpResult.getItems());
                                                        setResult(Config.SUCCESS);
                                                        finish();
                                                    }
                                                }
                                            });
                                }
                            }
                        });

                new HttpPresneter.Builder(HttpConfig.USER_AUTHEN, String.class, MineAuActivity.this)
                        .PartMap("userGuid", user.getGuid())
                        .PartMap("name", ((TextView) quickAdapter.getViewByPosition(8, R.id.tv_vertical_content)).getText().toString().trim())
                        .PartMap("idnum", ((TextView) quickAdapter.getViewByPosition(9, R.id.tv_vertical_content)).getText().toString().trim())
                        .PartMap("sex", "男".equals(sex.trim()) ? "0" : "1")
                        .PartMap("ptel", user.getUname())
                        .PartMap("nation", ((TextView) quickAdapter.getViewByPosition(12, R.id.tv_vertical_content)).getText().toString().trim())
                        .PartMap("date", ((TextView) quickAdapter.getViewByPosition(11, R.id.tv_vertical_content)).getText().toString().trim())
                        .PartMap("pnative", ((TextView) quickAdapter.getViewByPosition(4, R.id.tv_vertical_content)).getText().toString().trim())
                        .PartMap("mail", ((TextView) quickAdapter.getViewByPosition(7, R.id.tv_vertical_content)).getText().toString().trim())
                        .PartMap("rdate", ((TextView) quickAdapter.getViewByPosition(6, R.id.tv_vertical_content)).getText().toString().trim())
                        .PartMap("age", age + "")
                        .PartMap("user", user.getUname())
                        .PartMap("housetype", ((TextView) quickAdapter.getViewByPosition(5, R.id.tv_vertical_content)).getText().toString().trim())
                        .PartMap("houseadress", ((TextView) quickAdapter.getViewByPosition(13, R.id.tv_vertical_content)).getText().toString().trim())
                        .fileMap("iphoto", imagePathZhengjianzhao)
                        .fileMap("idumfrontphoto", imagePathIDCardFront)
                        .fileMap("idumbackphoto", imagePathIDCardBehand)
                        .fileMap("withidumphoto", imagePathIDCardWith)
                        .setOnHttpListener(new HttpPresneter.OnHttpListener() {
                            @Override
                            public void onError(Throwable e) {
                                System.out.println(e.toString());
                                ToastUtil.showShort(Config.SERVER_ERROR);
                            }

                            @Override
                            public void onNext(Object o) {
                                System.out.println(o.toString());

                            }
                        })
                        .build()
                        .formDataPost();

            } else {
                ToastUtil.showLong(msg);
            }
        });
    }

    private int getAge() {
        String trim = ((TextView) quickAdapter.getViewByPosition(11, R.id.tv_vertical_content)).getText().toString().trim();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = sf.parse(trim);
            Calendar birthCalendar = Calendar.getInstance();
            birthCalendar.setTime(date);
            Calendar nowCalendar = Calendar.getInstance();
            if (nowCalendar.get(Calendar.MONTH) == birthCalendar.get(Calendar.MONTH)) {
                if (nowCalendar.get(Calendar.DAY_OF_MONTH) >= birthCalendar.get(Calendar.DAY_OF_MONTH)) {
                    return nowCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR);
                } else {
                    return nowCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR) - 1;
                }
            } else if (nowCalendar.get(Calendar.MONTH) > birthCalendar.get(Calendar.MONTH)) {
                return nowCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR);
            } else {
                return nowCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR) - 1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private boolean checkInfo() {

        if (!isIDCardGet) {
            msg = "请上传清晰正确的身份证正面";
            return false;
        }
        if (TextUtils.isEmpty(imagePathIDCardFront)) {
            msg = "请上传身份证正面";
            return false;
        }
        if (TextUtils.isEmpty(imagePathIDCardBehand)) {
            msg = "请上传身份证反面";
            return false;
        }
        if (TextUtils.isEmpty(imagePathIDCardWith)) {
            msg = "请上传手持身份证";
            return false;
        }
        if (TextUtils.isEmpty(imagePathZhengjianzhao)) {
            msg = "请上传个人证件照";
            return false;
        }
        if (TextUtils.isEmpty(((TextView) quickAdapter.getViewByPosition(6, R.id.tv_vertical_content)).getText().toString().trim())) {
            msg = "请选择生日祝福日期";
            return false;
        }
        if (TextUtils.isEmpty(((TextView) quickAdapter.getViewByPosition(4, R.id.tv_vertical_content)).getText().toString().trim())) {
            msg = "请选择籍贯";
            return false;
        }
        if (TextUtils.isEmpty(((TextView) quickAdapter.getViewByPosition(5, R.id.tv_vertical_content)).getText().toString().trim())) {
            msg = "请选择户口性质";
            return false;
        }
        if (TextUtils.isEmpty(((TextView) quickAdapter.getViewByPosition(7, R.id.tv_vertical_content)).getText().toString().trim())) {
            msg = "请输入邮箱";
            return false;
        }
        return true;
    }

    @Override
    protected RecyclerView initRecyclerView() {
        return dataBinding.recyclerView;
    }

    @Override
    public void itemClick(int p) {
        switch (p) {
            case 0:
                PictureSelector.create(MineAuActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .compress(true)
                        .imageSpanCount(3)
                        .isCamera(false)
                        .selectionMedia(localList)
                        .forResult(120);
                break;
            case 1:
            case 2:
            case 3:
                choosed = p;
                PictureSelector.create(this)
                        .openCamera(PictureMimeType.ofImage())
                        .compress(true)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case 4:
                if (areaDialog == null) {
                    initAreaDialog();
                } else {
                    areaDialog.show();
                }
                break;
            case 6:
                startActivityForResult(SelectTimeWithLunarActivity.class, null, Config.SELECT_TIME_WITH_LUNAR);
                break;

        }
    }

    private void initAreaDialog() {
        OkGo.<List<AreaBean>>post(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "0")
                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .params("type", 0)
                .execute(new JsonCallBack<List<AreaBean>>() {
                    @Override
                    public void onSuccess(Response<List<AreaBean>> response) {
                        System.out.println("使用了网络请求");
                        areaBean = response.body();
                        areaDialog = new MultiChooseUtil().getAreaDialog(MineAuActivity.this, 3, areaBean, (d, a) -> {
                            areaDialog.dismiss();
                            String result = "";
                            for (ISelectAble iSelectAble : a) {
                                result += iSelectAble.getName();
                            }
                            String cityCode = areaBean.get(a.get(0).getId()).getSub().get(a.get(1).getId()).getCode();
                            String areaCode = areaBean.get(a.get(0).getId()).getSub().get(a.get(1).getId()).getSub().get(a.get(2).getId()).getCode();
                            editBeans.get(4).setContent(result + "-" + (cityCode == "0" ? areaCode : cityCode));
                            quickAdapter.notifyItemChanged(4);
                        });
                        areaDialog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<List<AreaBean>> response) {
                        System.out.println("使用了缓存");
                        areaBean = response.body();
                        areaDialog = new MultiChooseUtil().getAreaDialog(MineAuActivity.this, 3, areaBean, (d, a) -> {
                            areaDialog.dismiss();
                            String result = "";
                            for (ISelectAble iSelectAble : a) {
                                result += iSelectAble.getName();
                            }
                            String cityCode = areaBean.get(a.get(0).getId()).getSub().get(a.get(1).getId()).getCode();
                            String areaCode = areaBean.get(a.get(0).getId()).getSub().get(a.get(1).getId()).getSub().get(a.get(2).getId()).getCode();
                            editBeans.get(4).setContent(result + "-" + (cityCode == "0" ? areaCode : cityCode));
                            quickAdapter.notifyItemChanged(4);
                        });
                        areaDialog.show();
                    }
                });
    }

    @Override
    public void initData() {
        int index = 0;
        for (int i = 0; i < titles.length; i++) {
            EditBean editBean = new EditBean();
            editBean.setTitle(titles[i]);
            editBean.setType(types[i]);
            editBean.setContent("");
            editBean.setTextTip(tipTexts[i]);
            editBean.setTextTitle(titleTexts[i]);
            editBean.setHint(hintTexts[i]);
            editBean.setEnter(false);
            editBeans.add(editBean);
            if (index < decoders.length && i == decoders[index]) {
                index++;
                editBean.setBottom(true);
                editBean.setUnderLine(false);
            }
            if (i == 5) {
                String[] stringArray = getResources().getStringArray(R.array.hukouxingzhi);
                editBean.setChooseItem(stringArray);
            }
            if (i == 7) {
                ArrayList<Scheme> schemes = new ArrayList<>();
                schemes.add(StaticScheme.Email());
                editBean.setSchemes(schemes);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Config.SUCCESS) {
            switch (requestCode) {
                case Config.SELECT_TIME_WITH_LUNAR:
                    int month = data.getIntExtra(Config.MONTH, -1);
                    int day = data.getIntExtra(Config.DAY, -1);
                    int type = data.getIntExtra(Config.BIRTH_TYPE, -1);
                    editBeans.get(6).setContent((type == Config.LUNAR ? "阴历" : "阳历") + "-" + month + "-" + day);
                    quickAdapter.notifyItemChanged(6);
                    break;

            }
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    String outfile = selectList.get(0).getCompressPath();
                    switch (choosed) {
                        case 1:
                            imagePathIDCardFront = outfile;
                            checkIDCardPhoto(imagePathIDCardFront);
                            break;
                        case 2:
                            imagePathIDCardBehand = outfile;
                            editBeans.get(2).setContent("已选择");
                            quickAdapter.notifyItemChanged(2);
                            break;
                        case 3:
                            imagePathIDCardWith = outfile;
                            editBeans.get(3).setContent("已选择");
                            quickAdapter.notifyItemChanged(3);
                            break;
                    }
                    break;
                case 120:
                    selectList = PictureSelector.obtainMultipleResult(data);
                    localList.clear();
                    localList.add(selectList.get(0));
                    imagePathZhengjianzhao = selectList.get(0).getCompressPath();
                    editBeans.get(0).setContent("已选择");
                    quickAdapter.notifyItemChanged(0);

            }
        }
    }

    private void checkIDCardPhoto(String path) {
        Observable.just(1)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((i) -> {
                    PhotoHttpUtil.getPhotoInfo(this, path, new HttpPresneter.OnHttpListener<IDCardBean.CardsBean>() {
                        @Override
                        public void onError(Throwable e) {
                            System.out.println(e.toString());
                            ToastUtil.showShort("证件未识别，请重试");
                            isIDCardGet = false;
                        }

                        @Override
                        public void onNext(IDCardBean.CardsBean cardsBean) {
                            editBeans.get(8).setContent(cardsBean.getName());
                            editBeans.get(9).setContent(cardsBean.getId_card_number());
                            editBeans.get(10).setContent(cardsBean.getGender());
                            editBeans.get(11).setContent(cardsBean.getBirthday());
                            editBeans.get(12).setContent(cardsBean.getRace());
                            editBeans.get(13).setContent(cardsBean.getAddress());
                            editBeans.get(1).setContent("已选择");
                            refresh();
                            isIDCardGet = true;
                        }
                    });
                });
    }

    @Override
    public void recoverData() {
        super.recoverData();
        String s = "";
        s = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathIDCardFront", "");
        if (!TextUtils.isEmpty(s)) {
            imagePathIDCardFront = s;
        }
        s = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathZhengjianzhao", "");
        if (!TextUtils.isEmpty(s)) {
            imagePathZhengjianzhao = s;
        }
        s = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathIDCardBehand", "");
        if (!TextUtils.isEmpty(s)) {
            imagePathIDCardBehand = s;
        }
        s = (String) SPUtil.getParam(getLocalClassName() + user.getUname() + "imagePathIDCardWith", "");
        if (!TextUtils.isEmpty(s)) {
            imagePathIDCardWith = s;
        }
        isIDCardGet = (Boolean) SPUtil.getParam(getLocalClassName() + user.getUname() + "isIDCardGet", false);


        List<LocalMedia> object = (List<LocalMedia>) SPUtil.getParam(getLocalClassName() + user.getUname() + "localList");
        if (object != null) {
            localList = object;
        }
    }

    @Override
    public void clearData() {
        super.clearData();
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardFront", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathZhengjianzhao", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardWith", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardBehand", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "localList", Config.NULL);
        SPUtil.setParam(getLocalClassName() + user.getUname() + "isIDCardGet", false);
    }

    @Override
    public void saveData() {
        super.saveData();
        if (!TextUtils.isEmpty(imagePathIDCardFront)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardFront", imagePathIDCardFront);
        }
        if (!TextUtils.isEmpty(imagePathZhengjianzhao)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathZhengjianzhao", imagePathZhengjianzhao);
        }
        if (!TextUtils.isEmpty(imagePathIDCardWith)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardWith", imagePathIDCardWith);
        }
        if (!TextUtils.isEmpty(imagePathIDCardBehand)) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "imagePathIDCardBehand", imagePathIDCardBehand);
        }
        if (localList != null) {
            SPUtil.setParam(getLocalClassName() + user.getUname() + "localList", localList);
        }
        SPUtil.setParam(getLocalClassName() + user.getUname() + "isIDCardGet", isIDCardGet);
    }
}